package com.ysd.lis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.common.dto.OrganizationDTO;
import com.ysd.constant.AlphabetArray;
import com.ysd.lis.dto.InterfaceDto;
import com.ysd.lis.entity.*;
import com.ysd.lis.mapper.SysInterfaceDictMapper;
import com.ysd.lis.mapper.SysInterfaceDictParamMapper;
import com.ysd.lis.mapper.SysInterfaceMethodOutparamMapper;
import com.ysd.lis.mapper.sys.*;
import com.ysd.lis.request.InterfaceParam;
import com.ysd.lis.service.*;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.t_user 服务实现类
 * </p>
 *
 * @author peng
 * @since 2022-04-24
 */
@Service
@Slf4j
public class SysInterfaceServiceImpl extends ServiceImpl<SysInterfaceMapper, SysInterface> implements SysInterfaceService {

    @Autowired
    SysInterfaceMapper sysInterfaceMapper;
    @Autowired
    SysInterfaceMethodMapper sysInterfaceMethodMapper;

    @Autowired
    SysInterfaceMethodService sysInterfaceMethodService;
    @Autowired
    SysInterfaceDictMapper sysInterfaceDictMapper;
    @Autowired
    SysInterfaceDictService sysInterfaceDictService;
    @Autowired
    SysOrganizationMapper sysOrganizationMapper;

    @Autowired
    SysInterfaceCaUserMapper sysInterfaceCaUserMapper;
    @Autowired
    SysInterfaceDictFieldMapper sysInterfaceDictFieldMapper;
    @Autowired
    SysInterfaceDictFieldService sysInterfaceDictFieldService;
    @Autowired
    SysInterfaceDictParamMapper sysInterfaceDictParamMapper;
    @Autowired
    SysInterfaceDictParamService sysInterfaceDictParamService;
    @Autowired
    SysInterfaceMethExtParamMapper sysInterfaceMethExtParamMapper;
    @Autowired
    SysInterfaceMethExtParamService sysInterfaceMethExtParamService;
    @Autowired
    SysInterfaceMethValueMapper sysInterfaceMethValueMapper;
    @Autowired
    SysInterfaceMethValueService sysInterfaceMethValueService;
    @Autowired
    SysInterfaceMethodOutparamMapper sysInterfaceMethodOutparamMapper;
    @Autowired
    SysInterfaceMethodOutparamService sysInterfaceMethodOutparamService;
    /**复制*/

    /**
     * SYS_INTERFACE **
     * SYS_INTERFACE_CA_USER    √
     * SYS_INTERFACE_DICT **
     * SYS_INTERFACE_DICT_FIELD √
     * SYS_INTERFACE_DICT_PARAM √
     * SYS_INTERFACE_EVENT_LOG ×
     * SYS_INTERFACE_EXCEPTIONAL_LOG ×
     * SYS_INTERFACE_FUNCTION   --
     * SYS_INTERFACE_METH_EXT_PARAM √
     * SYS_INTERFACE_METH_VALUE √
     * SYS_INTERFACE_METHOD **
     * SYS_INTERFACE_METHOD_OUTPARAM
     */

    @Override
    public Result findSysInterfaceList(InterfaceParam param) {
        MPJLambdaWrapper<SysInterface> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(SysInterface.class).eq(SysInterface::getDelFlag, 0);

        if (StringUtils.isNotBlank(param.getSeachValue())) {
            queryWrapper.and(wrapper -> wrapper.like(SysInterface::getInterfaceCode, param.getSeachValue()).or().like(SysInterface::getInterfaceName, param.getSeachValue()));
        }
        if (StringUtils.isNotBlank(param.getModuleId())) {
            queryWrapper.eq(SysInterface::getModuleId, param.getModuleId());
        }
        if (StringUtils.isNotBlank(param.getTypeNo())) {
            queryWrapper.eq(SysInterface::getTypeNo, param.getTypeNo());
        }
        queryWrapper.eq(StringUtils.isNotBlank(param.getSystemId()), SysInterface::getSystemId, param.getSystemId());


        queryWrapper.orderByAsc(SysInterface::getSeq);
        List<SysInterface> interfaceList = sysInterfaceMapper.selectList(queryWrapper);

        //查询出所有的机构
        LambdaQueryWrapper<SysOrganization> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysOrganization::getDelFlag, 0);
        List<SysOrganization> sysOrganizations = sysOrganizationMapper.selectList(lambdaQueryWrapper);

        interfaceList.forEach(a -> {
            Optional<SysOrganization> first = sysOrganizations.stream().filter(s -> a.getHospId().equals(s.getId())).findFirst();
            if (first.isPresent()) {
                a.setHospName(first.get().getName());
            }
        });


        return Result.succ(1, "查询成功", interfaceList);
    }

    @Override
    public Result addInterface(SysInterface sysInterface) {
        int insert = sysInterfaceMapper.insert(sysInterface);
        //新增接口的时候插入method方法
//        LambdaQueryWrapper<SysInterfaceDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(SysInterfaceDict::getOwnSystem,sysInterface.getModuleId())
//                .eq(SysInterfaceDict::getInterfaceGroup,sysInterface.getSystemId())
//                .eq(SysInterfaceDict::getType,sysInterface.getInterfaceType())
//                .eq(SysInterfaceDict::getDelFlag,0);
//
//        List<SysInterfaceDict> sysInterfaceDicts = sysInterfaceDictMapper.selectList(lambdaQueryWrapper);
//
//        List<SysInterfaceMethod> dataList = new ArrayList<>();
//        if(CollectionUtils.isNotEmpty(sysInterfaceDicts)){
//            sysInterfaceDicts.forEach(a->{
//                SysInterfaceMethod sysInterfaceMethod = new SysInterfaceMethod();
//                sysInterfaceMethod.setInterfaceDictId(a.getId());
//                sysInterfaceMethod.setInterfaceId(sysInterface.getId());
//                sysInterfaceMethod.setIsEnable(false);
//                sysInterfaceMethod.setIsSet(1);
//                dataList.add(sysInterfaceMethod);
//            });
//            sysInterfaceMethodService.saveBatch(dataList);
//        }
        if (insert > 0) {
            return Result.succ(1, "添加成功", sysInterface);
        } else {
            return Result.fail(400, "添加失败", "");
        }
    }

    @Override
    public Result editInterface(SysInterface sysInterface) {
        int updateById = sysInterfaceMapper.updateById(sysInterface);
        if (updateById > 0) {
            return Result.succ(1, "提交成功", sysInterface);
        } else {
            return Result.fail(400, "修改失败", "");
        }
    }

    @Override
    public Result deleteInterface(SysInterface sysInterface) {
        int deleteById = sysInterfaceMapper.deleteById(sysInterface.getId());
        if (deleteById > 0) {
            return Result.succ(1, "删除成功", "");
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }

    @Override
    public Result batchDeleteInterfaceList(InterfaceDto dto) {
        List<SysInterface> interfaceList = dto.getInterfaceList();
        List<String> ids = interfaceList.stream().map(SysInterface::getId).collect(Collectors.toList());

        LambdaQueryWrapper<SysInterfaceMethod> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysInterfaceMethod::getDelFlag, 0).in(SysInterfaceMethod::getInterfaceId, ids);
        Integer cnt = sysInterfaceMethodMapper.selectCount(queryWrapper);
        if (cnt > 0) {
            return Result.fail(400, "接口下有明细，不能删除", null);
        }

        boolean b = this.removeByIds(ids);
        if (b) {
            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }

    @Override
    public Boolean copyPasteInterfaceData(OrganizationDTO input) {
        try {
            LambdaQueryWrapper<SysInterface> qoeryInterface = new LambdaQueryWrapper<>();
            qoeryInterface.eq(SysInterface::getDelFlag, 0);
            qoeryInterface.eq(SysInterface::getOrgId, input.getSourceOrgId());

            LambdaQueryWrapper<SysInterfaceDict> qoeryInterfaceDict = new LambdaQueryWrapper<>();
            qoeryInterfaceDict.eq(SysInterfaceDict::getDelFlag, 0);
            qoeryInterfaceDict.eq(SysInterfaceDict::getOrgId, input.getSourceOrgId());

            LambdaQueryWrapper<SysInterfaceDictField> qoeryInterfaceDictField = new LambdaQueryWrapper<>();
            qoeryInterfaceDictField.eq(SysInterfaceDictField::getDelFlag, 0);
            qoeryInterfaceDictField.eq(SysInterfaceDictField::getOrgId, input.getSourceOrgId());

            LambdaQueryWrapper<SysInterfaceDictParam> qoerySysInterfaceDictParam = new LambdaQueryWrapper<>();
            qoerySysInterfaceDictParam.eq(SysInterfaceDictParam::getDelFlag, 0);
            qoerySysInterfaceDictParam.eq(SysInterfaceDictParam::getOrgId, input.getSourceOrgId());

            LambdaQueryWrapper<SysInterfaceMethExtParam> qoerySysInterfaceMethExtParam = new LambdaQueryWrapper<>();
            qoerySysInterfaceMethExtParam.eq(SysInterfaceMethExtParam::getDelFlag, 0);
            qoerySysInterfaceMethExtParam.eq(SysInterfaceMethExtParam::getOrgId, input.getSourceOrgId());

            LambdaQueryWrapper<SysInterfaceMethValue> qoerySysInterfaceMethValue = new LambdaQueryWrapper<>();
            qoerySysInterfaceMethValue.eq(SysInterfaceMethValue::getDelFlag, 0);
            qoerySysInterfaceMethValue.eq(SysInterfaceMethValue::getOrgId, input.getSourceOrgId());

            LambdaQueryWrapper<SysInterfaceMethodOutparam> qoerySysInterfaceMethodOutparam = new LambdaQueryWrapper<>();
            qoerySysInterfaceMethodOutparam.eq(SysInterfaceMethodOutparam::getDelFlag, 0);
            qoerySysInterfaceMethodOutparam.eq(SysInterfaceMethodOutparam::getOrgId, input.getSourceOrgId());


            List<SysInterface> lstSysInterface = sysInterfaceMapper.selectList(qoeryInterface);
            List<SysInterfaceDict> lstSysInterfaceDict = sysInterfaceDictMapper.selectList(qoeryInterfaceDict);
            List<SysInterfaceDictField> lstInterfaceDictField = sysInterfaceDictFieldMapper.selectList(qoeryInterfaceDictField);
            List<SysInterfaceDictParam> lstSysInterfaceDictParam = sysInterfaceDictParamMapper.selectList(qoerySysInterfaceDictParam);
            List<SysInterfaceMethExtParam> lstSysInterfaceMethExtParam = sysInterfaceMethExtParamMapper.selectList(qoerySysInterfaceMethExtParam);
            List<SysInterfaceMethValue> lstSysInterfaceMethValue = sysInterfaceMethValueMapper.selectList(qoerySysInterfaceMethValue);
            List<SysInterfaceMethodOutparam> lstSysInterfaceMethodOutparam = sysInterfaceMethodOutparamMapper.selectList(qoerySysInterfaceMethodOutparam);

            String sourceOrgId = input.getSourceOrgId();
            String goalOrgId = input.getGoalOrgId();
            Integer orgIndex = input.getOrgIndex();
            String s = AlphabetArray.Alphabet[orgIndex];

            /*接口服务*/
            sysInterfaceMapper.delete(new LambdaQueryWrapper<SysInterface>().eq(SysInterface::getOrgId, goalOrgId));
            List<SysInterface> listArr1 = new ArrayList<>();
            for (SysInterface m : lstSysInterface) {
                //复制模块
                SysInterface op = new SysInterface();
                BeanUtil.copyProperties(m, op, "id", "orgId","moduleId","hospId");
                op.setOrgId(goalOrgId);
                String id = m.getId();
                String newId = s + id.substring(s.length());
                op.setId(newId);

                String moduleId = m.getModuleId();
                if(ToolsUtils.isNotEmpty(moduleId)){
                    String newmoduleId = s + moduleId.substring(s.length());
                    op.setModuleId(newmoduleId);
                }

                String hospId = m.getHospId();
                if(ToolsUtils.isNotEmpty(hospId)){
                    String newhospId = s + hospId.substring(s.length());
                    op.setHospId(newhospId);
                }
                listArr1.add(op);
            }
            this.saveBatch(listArr1);

            /*接口字典*/
            sysInterfaceDictMapper.delete(new LambdaQueryWrapper<SysInterfaceDict>().eq(SysInterfaceDict::getOrgId, goalOrgId));
            List<SysInterfaceDict> listArr2 = new ArrayList<>();
            for (SysInterfaceDict m : lstSysInterfaceDict) {
                //复制模块
                SysInterfaceDict op = new SysInterfaceDict();
                BeanUtil.copyProperties(m, op, "id", "orgId","ownSystem");
                op.setOrgId(goalOrgId);

                String id = m.getId();
                String newId = s + id.substring(s.length());
                op.setId(newId);

                String ownSystem = m.getOwnSystem();
                if(ToolsUtils.isNotEmpty(ownSystem)){
                    String newOwnSystem = s + ownSystem.substring(s.length());
                    op.setOwnSystem(newOwnSystem);
                }
                listArr2.add(op);
//                String interfaceGroup = m.getInterfaceGroup();
//                if(ToolsUtils.isNotEmpty(interfaceGroup)){
//                    String[] split = interfaceGroup.split(",");
//                    String newInterfaceGroup = "";
//                    for (String str : split) {
//                        String newStr = s + str.substring(s.length());
//                        newInterfaceGroup += newStr + ",";
//                    }
//                    op.setInterfaceGroup(newInterfaceGroup.substring(0, newInterfaceGroup.length()-1));
//
//                }
            }
            sysInterfaceDictService.saveBatch(listArr2);

            /*接口字典*/
            sysInterfaceDictFieldMapper.delete(new LambdaQueryWrapper<SysInterfaceDictField>().eq(SysInterfaceDictField::getOrgId, goalOrgId));
            List<SysInterfaceDictField> listArr3 = new ArrayList<>();
            for (SysInterfaceDictField m : lstInterfaceDictField) {
                //复制模块
                SysInterfaceDictField op = new SysInterfaceDictField();
                BeanUtil.copyProperties(m, op, "id", "orgId");
                op.setOrgId(goalOrgId);
                String id = m.getId();
                String newId = s + id.substring(s.length());
                op.setId(newId);

                String pid = m.getPid();
                if(ToolsUtils.isNotEmpty(pid)){
                    String newpid = s + pid.substring(s.length());
                    op.setPid(newpid);
                }

                listArr3.add(op);
            }
            sysInterfaceDictFieldService.saveBatch(listArr3);

            /*接口字典*/
            sysInterfaceDictParamMapper.delete(new LambdaQueryWrapper<SysInterfaceDictParam>().eq(SysInterfaceDictParam::getOrgId, goalOrgId));
            List<SysInterfaceDictParam> listArr4 = new ArrayList<>();
            for (SysInterfaceDictParam m : lstSysInterfaceDictParam) {
                //复制模块
                SysInterfaceDictParam op = new SysInterfaceDictParam();
                BeanUtil.copyProperties(m, op, "id", "orgId","dictId","parentId");
                op.setOrgId(goalOrgId);

                String id = m.getId();
                String newId = s + id.substring(s.length());
                op.setId(newId);

                String dictId = m.getDictId();
                if(ToolsUtils.isNotEmpty(dictId)){
                    String newdictId = s + dictId.substring(s.length());
                    op.setDictId(newdictId);
                }

                String pid = m.getParentId();
                if(ToolsUtils.isNotEmpty(pid)){
                    String newpid = s + pid.substring(s.length());
                    op.setParentId(newpid);
                }

                listArr4.add(op);
            }
            sysInterfaceDictParamService.saveBatch(listArr4);

            /*接口字典*/
            sysInterfaceMethExtParamMapper.delete(new LambdaQueryWrapper<SysInterfaceMethExtParam>().eq(SysInterfaceMethExtParam::getOrgId, goalOrgId));
            List<SysInterfaceMethExtParam> listArr5 = new ArrayList<>();
            for (SysInterfaceMethExtParam m : lstSysInterfaceMethExtParam) {
                //复制模块
                SysInterfaceMethExtParam op = new SysInterfaceMethExtParam();
                BeanUtil.copyProperties(m, op, "id", "orgId" ,"inCodeId","interfaceMethodId","interfaceId","interfaceMethodDictId");
                op.setOrgId(goalOrgId);

                String id = m.getId();
                String newId = s + id.substring(s.length());
                op.setId(newId);

                String inCodeId = m.getInCodeId();
                if(ToolsUtils.isNotEmpty(inCodeId)){
                    String newinCodeId = s + inCodeId.substring(s.length());
                    op.setInCodeId(newinCodeId);
                }
                String interfaceMethodId = m.getInterfaceMethodId();
                if(ToolsUtils.isNotEmpty(interfaceMethodId)){
                    String newinterfaceMethodId = s + interfaceMethodId.substring(s.length());
                    op.setInterfaceMethodId(newinterfaceMethodId);
                }
                String interfaceId = m.getInterfaceId();
                if(ToolsUtils.isNotEmpty(interfaceId)){
                    String newinterfaceId = s + interfaceId.substring(s.length());
                    op.setInterfaceId(newinterfaceId);
                }
                String interfaceMethodDictId = m.getInterfaceMethodDictId();
                if(ToolsUtils.isNotEmpty(interfaceMethodDictId)){
                    String newinterfaceMethodDictId = s + interfaceMethodDictId.substring(s.length());
                    op.setInterfaceMethodDictId(newinterfaceMethodDictId);
                }


                listArr5.add(op);
            }
            sysInterfaceMethExtParamService.saveBatch(listArr5);

            /*接口字典*/
            sysInterfaceMethValueMapper.delete(new LambdaQueryWrapper<SysInterfaceMethValue>().eq(SysInterfaceMethValue::getOrgId, goalOrgId));
            List<SysInterfaceMethValue> listArr6 = new ArrayList<>();
            for (SysInterfaceMethValue m : lstSysInterfaceMethValue) {
                //复制模块
                SysInterfaceMethValue op = new SysInterfaceMethValue();
                BeanUtil.copyProperties(m, op, "id", "orgId", "methodId","interfaceId","fieldId","dictId");
                op.setOrgId(goalOrgId);

                String id = m.getId();
                String newId = s + id.substring(s.length());
                op.setId(newId);

                String methodId = m.getMethodId();
                if(ToolsUtils.isNotEmpty(methodId)){
                    String newmethodId = s + methodId.substring(s.length());
                    op.setMethodId(newmethodId);
                }
                String interfaceId = m.getInterfaceId();
                if(ToolsUtils.isNotEmpty(interfaceId)){
                    String newinterfaceId = s + interfaceId.substring(s.length());
                    op.setInterfaceId(newinterfaceId);
                }
                String fieldId = m.getFieldId();
                if(ToolsUtils.isNotEmpty(fieldId)){
                    String newfieldId = s + fieldId.substring(s.length());
                    op.setFieldId(newfieldId);
                }
                String dictId = m.getDictId();
                if(ToolsUtils.isNotEmpty(dictId)){
                    String newdictId = s + dictId.substring(s.length());
                    op.setDictId(newdictId);
                }

                listArr6.add(op);
            }
            sysInterfaceMethValueService.saveBatch(listArr6);

            /*接口字典*/
            sysInterfaceMethodOutparamMapper.delete(new LambdaQueryWrapper<SysInterfaceMethodOutparam>().eq(SysInterfaceMethodOutparam::getOrgId, goalOrgId));
            List<SysInterfaceMethodOutparam> listArr7 = new ArrayList<>();
            for (SysInterfaceMethodOutparam m : lstSysInterfaceMethodOutparam) {
                //复制模块
                SysInterfaceMethodOutparam op = new SysInterfaceMethodOutparam();
                BeanUtil.copyProperties(m, op, "id", "orgId","interfaceId","methodId");
                op.setOrgId(goalOrgId);

                String id = m.getId();
                String newId = s + id.substring(s.length());
                op.setId(newId);

                String interfaceId = m.getInterfaceId();
                if(ToolsUtils.isNotEmpty(interfaceId)){
                    String newinterfaceId = s + interfaceId.substring(s.length());
                    op.setInterfaceId(newinterfaceId);
                }
                String methodId = m.getMethodId();
                if(ToolsUtils.isNotEmpty(methodId)){
                    String newmethodId = s + methodId.substring(s.length());
                    op.setMethodId(newmethodId);
                }


                listArr7.add(op);
            }
            sysInterfaceMethodOutparamService.saveBatch(listArr7);

            //根据传过来的goalOrgId删除方法
            sysInterfaceMethodMapper.delete(new LambdaQueryWrapper<SysInterfaceMethod>().eq(SysInterfaceMethod::getOrgId, goalOrgId));

            //根据传过来的sourceOrgId查出所有的方法
            List<SysInterfaceMethod> sysInterfaceMethods = sysInterfaceMethodMapper.selectList(new LambdaQueryWrapper<SysInterfaceMethod>().eq(SysInterfaceMethod::getOrgId, sourceOrgId).eq(SysInterfaceMethod::getDelFlag, 0));

            List<SysInterfaceMethod> addMethodList = new ArrayList<>();
            for (SysInterfaceMethod m : sysInterfaceMethods) {
                //复制接口方法
                SysInterfaceMethod op = new SysInterfaceMethod();
                BeanUtil.copyProperties(m, op, "id", "orgId","interfaceId","interfaceDictId");
                op.setOrgId(goalOrgId);

                String id = m.getId();
                String newId = s + id.substring(s.length());
                op.setId(newId);

                String interfaceId = m.getInterfaceId();
                if(ToolsUtils.isNotEmpty(interfaceId)){
                    String newinterfaceId = s + interfaceId.substring(s.length());
                    op.setInterfaceId(newinterfaceId);
                }
                String interfaceDictId = m.getInterfaceDictId();
                if(ToolsUtils.isNotEmpty(interfaceDictId)){
                    String newinterfaceDictId = s + interfaceDictId.substring(s.length());
                    op.setInterfaceDictId(newinterfaceDictId);
                }
                addMethodList.add(op);

            }
            sysInterfaceMethodService.saveBatch(addMethodList);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //todo
        }
        return null;
    }
}
